package com.example.tool.util;

import com.alibaba.fastjson.JSONObject;
import com.example.tool.bean.weather.WeatherMojiCommonResponse;
import com.example.tool.util.aliyun.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class WeatherMojiUtil {

    // 密钥
    private static final String appCode = "18db0191d2014626967ada0fb1acd5f4";
    private static final String token = "f9f212e1996e79e0e602b08ea297ffb0";
    // 调用地址
    private static final String mojiHost = "https://aliv18.data.moji.com";
    private static final String forecast15daysPath = "/whapi/json/alicityweather/forecast15days";

    /**
     * 获取墨迹15天天气
     */
    public static WeatherMojiCommonResponse queryForecastWeather15(Integer cityId) {
        if (cityId == null) {
            throw new RuntimeException("墨迹城市ID不能为空");
        }
        String method = "POST";
        String headAppCode = "APPCODE " + appCode;
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", headAppCode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> queryMap = new HashMap<>();
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("token", token);
        bodyMap.put("cityId", String.valueOf(cityId));
        try {
            HttpResponse response = HttpUtils.doPost(mojiHost, forecast15daysPath, method, headers, queryMap, bodyMap);
            String result = EntityUtils.toString(response.getEntity());
            log.info("查询预报天气结果返回:{}", result);
            return JSONObject.parseObject(result, WeatherMojiCommonResponse.class);
        } catch (Exception e) {
            log.error("查询预报天气异常:", e);
            throw new RuntimeException(e);
        }
    }

}
